<?php
/*
 * 模型基类
 */
namespace app\common;
use Yii;
class PopToolActiveRecord extends \yii\db\ActiveRecord {

	/**
	 * 所有数据库连接key
	 * @var array
	 */
	public static $pop_dbKeys = [];

	/**
	 * 事务开启状态
	 * @var bool
	 */
	public static $pop_transOn = false;

	/**
	 * 给对象赋值
	 * @param $data
	 */
	public function setData($datas,$fields = '') {

		if (!empty($fields)) {
			$fields = is_array($fields) ? $fields : explode(',',$fields);
		}

		if (empty($fields)) {
			foreach ($datas as $key=>$val) {
				$this->$key = $val;
			}

		} else {
			foreach ($fields as $field) {
				$this->$field = $datas[$field];
			}
		}
		return $this;
	}

	/**
	 * 启动事务
	 * 开启事务之前，提交之前的事务
	 * @return
	 */
	public static function beginTransaction() {
		self::commit();
		if (self::$pop_transOn === false) {//如果事务已经开启
			self::$pop_transOn = true;
			$transaction = self::getDb()->beginTransaction();
			self::$pop_dbKeys =  $transaction;
		}
	}

	/**
	 * 提交事务
	 * @return
	 */
	public static function commit() {
		if (self::$pop_transOn === true) {
			self::$pop_transOn = false;
			self::$pop_dbKeys->commit();
		}

		return ;
	}

	/**
	 * 回滚事务
	 * @return
	 */
	public static function rollback() {
		if (self::$pop_transOn === true) {
			self::$pop_transOn = false;
			self::$pop_dbKeys->rollback();
		}

		return ;
	}

	/**
	 * 格式化分页
	 * @param array $data
	 * @param int $count
	 */
	public static function formatPage($data = [],$count = 0) {
		return ['datalist'=>$data,'total_results'=>$count];
	}
}
